package com.mitchellbosecke.benchmark;

import com.mitchellbosecke.benchmark.model.Stock;
import org.openjdk.jmh.annotations.*;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Threads(1)
@Fork(1)
@Warmup(iterations = 7, time = 1)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Benchmark)
public abstract class BaseBenchmark {

    private static boolean benchmarking = false;

    static {
        URL url = BaseBenchmark.class.getResource("BaseBenchmark.class");
        String s = url.toString();
        if (s.contains("jar!")) {
            benchmarking = true;
        }
    }

    protected ThreadLocal<ByteArrayOutputStream> osStore = ThreadLocal.withInitial(() -> new ByteArrayOutputStream());

    protected Map<String, Object> getContext() {
        Map<String, Object> context = new HashMap<>();
        context.put("items", Stock.dummyItems());
        return context;
    }

    @Benchmark
    public final String benchmark() throws Exception {
        ByteArrayOutputStream os = osStore.get();
        os.reset();
        render(os);
        return benchmarking ? "" : os.toString();
    }

    protected abstract void render(OutputStream os) throws Exception;

}
